package br.ufrj.ppgi.jemf_basic_example;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import br.ufrj.ppgi.jemf_basic_example.fragments.AffectedOrganizationFragment;
import br.ufrj.ppgi.jemf_basic_example.fragments.CommanderFragment;
import br.ufrj.ppgi.jemf_basic_example.fragments.ContactFragment;
import br.ufrj.ppgi.jemf_basic_example.fragments.EmergencyFragment;
import br.ufrj.ppgi.jemf_basic_example.fragments.EquipmentFragment;
import br.ufrj.ppgi.jemf_basic_example.fragments.HealthCareUnitFragment;
import br.ufrj.ppgi.jemf_basic_example.fragments.LocationFragment;
import br.ufrj.ppgi.jemf_basic_example.fragments.MedicalFragment;
import br.ufrj.ppgi.jemf_basic_example.fragments.MissionFragment;
import br.ufrj.ppgi.jemf_basic_example.fragments.PlanFragment;
import br.ufrj.ppgi.jemf_basic_example.fragments.ResponderFragment;
import br.ufrj.ppgi.jemf_basic_example.fragments.TaskFragment;
import br.ufrj.ppgi.jemf_basic_example.fragments.TeamFragment;
import br.ufrj.ppgi.jemf_basic_example.fragments.TextMessageFragment;
import br.ufrj.ppgi.jemf_basic_example.fragments.VictimFragment;
import br.ufrj.ppgi.jemf_basic_example.fragments.VolunteerFragment;
import br.ufrj.ppgi.jemf_basic_example.fragments.WitnessFragment;

public class MainActivity extends Activity {

	// Main layout.
	private DrawerLayout mDrawerLayout;
	// Menu list.
	private ListView mDrawerList;
	// Main action bar button.
	private ActionBarDrawerToggle mDrawerToggle;

	// Nav drawer title.
	private CharSequence mDrawerTitle;
	// Used to store App title.
	private CharSequence mTitle;
	// Slide menu items.
	private String[] navMenuTitles;
	// Slide menu icons.
	private TypedArray navMenuIcons;
	// Menu item list.
	private ArrayList<NavDrawerItem> navDrawerItems;
	// Menu adapter.
	private NavDrawerListAdapter adapter;



	// Clicking TWICE the back button to exit activity.
    private static final long delay = 2000L;
    private boolean mRecentlyBackPressed = false;
    private Handler mExitHandler = new Handler();
    private Runnable mExitRunnable = new Runnable() {
        @Override
        public void run() {
            mRecentlyBackPressed=false;   
        }
    };



	public String[] tabs = { 
			"Emergency",
			"Mission",
			"Task",
			"Affected Organization",
			"Health Care Unit",
			"Equipment",
			"Location",
			"Commander",
			"Medical",
			"Responder",
			"Volunteer",
			"Victim",
			"Witness",
			"Contact",
			"Plan",
			"TextMessage",
			"Team"
	};



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);



		// Get the current App Title.
		mTitle = mDrawerTitle = getTitle();
		// Load slide menu items.
		navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
		// Nav drawer icons from resources.
		navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
		// Main Layout.
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		// Menu list view.
		mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

		// Adding Nav drawer items to array.
		navDrawerItems = new ArrayList<NavDrawerItem>();
		for(int i = 0; i < navMenuTitles.length ; i++){
			navDrawerItems.add(new NavDrawerItem(navMenuTitles[i], navMenuIcons.getResourceId(i, -1)));
		}	

		// Recycle the typed array.
		navMenuIcons.recycle();
		// Setting the menu listener. 
		mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
		// Setting the Nav drawer list adapter.
		adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems);
		mDrawerList.setAdapter(adapter);
		// Enabling action bar App icon and behaving it as toggle button.
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);


		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				// Nav menu toggle icon.
				R.drawable.ic_drawer,
				// Nav drawer open - description for accessibility.
				R.string.app_name,
				// Nav drawer close - description for accessibility.
				R.string.app_name) {

			@Override
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				// Calling onPrepareOptionsMenu() to show action bar icons.
				invalidateOptionsMenu();
			}

			@Override
			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				// Calling onPrepareOptionsMenu() to hide action bar icons.
				invalidateOptionsMenu();
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		if (savedInstanceState == null) {
			// On first time display view for first Nav item.
			displayView(0);
		}
	}

	/*
	 * Slide menu item click listener.
	 */
	private class SlideMenuClickListener implements ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			// Display view for selected Nav drawer item.
			displayView(position);
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Toggle Nav drawer on selecting action bar app icon/title.
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		// Handle action bar actions click.
		switch (item.getItemId()) {
			case R.id.action_info:
				AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
				// Setting Dialog Title.
				alertDialog.setTitle("Info About");
				// Setting Dialog Message.
				alertDialog.setMessage("Java Emergency Management Framework (JEMF), \n" +
										"Basic Example. \n\n" +
										"Created by Marcus Machado, \n" +
										"Federal University of Rio de Janeiro (UFRJ): \n" +
										"marcus.machado@ppgi.ufrj.br \n\n" +
										"This program is free software under " +
										"General Public License version 3 or later.");
				// Setting Icon to Dialog.
				alertDialog.setIcon(R.drawable.ic_launcher);
				// Setting OK Button.
				alertDialog.setButton(RESULT_OK, "OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// After dialog closed.
					}
				});
		        // Showing Alert Message.
		        alertDialog.show();
				return true;
			default:
				return super.onOptionsItemSelected(item);
		}
	}

	/*
	 * Called when invalidateOptionsMenu() is triggered.
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// If Nav drawer is opened, hide the action items.
		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		menu.findItem(R.id.action_info).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	/*
	 * Displaying fragment view for selected Nav drawer list item.
	 */
	private void displayView(int position) {
		// Update the main content by replacing fragments.
		Fragment fragment = null;
		switch (position) {
		case 0:
			// Emergency fragment activity.
			fragment = new EmergencyFragment();
			break;
		case 1:
			// Mission fragment activity.
			fragment = new MissionFragment();
			break;
		case 2:
			// Task fragment activity.
			fragment = new TaskFragment();
			break;
		case 3:
			// Affected Organization fragment activity.
			fragment = new AffectedOrganizationFragment();
			break;
		case 4:
			// Health Care Unit fragment activity.
			fragment = new HealthCareUnitFragment();
			break;
		case 5:
			// Equipment fragment activity.
			fragment = new EquipmentFragment();
			break;
		case 6:
			// Location fragment activity.
			fragment = new LocationFragment();
			break;
		case 7:
			// Commander fragment activity.
			fragment = new CommanderFragment();
			break;
		case 8:
			// Medical fragment activity.
			fragment = new MedicalFragment();
			break;
		case 9:
			// Responder fragment activity.
			fragment = new ResponderFragment();
			break;
		case 10:
			// Volunteer fragment activity.
			fragment = new VolunteerFragment();
			break;
		case 11:
			// Victim fragment activity.
			fragment = new VictimFragment();
			break;
		case 12:
			// Witness fragment activity.
			fragment = new WitnessFragment();
			break;
		case 13:
			// Contact fragment activity.
			fragment = new ContactFragment();
			break;
		case 14:
			// Plan fragment activity.
			fragment = new PlanFragment();
			break;
		case 15:
			// TextMessage fragment activity.
			fragment = new TextMessageFragment();
			break;
		case 16:
			// Team fragment activity.
			fragment = new TeamFragment();
			break;

		default:
			break;
		}

		if (fragment != null) {
            // Launching fragment selected.
			FragmentManager fragmentManager = getFragmentManager();
			fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();

			// Update selected item and title, then close the drawer.
			mDrawerList.setItemChecked(position, true);
			mDrawerList.setSelection(position);
			setTitle(navMenuTitles[position]);
			mDrawerLayout.closeDrawer(mDrawerList);
		} else {
			// Error in creating fragment.
			Log.e("MainActivity", "Error in creating fragment.");
		}
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	/*
	 * When using the ActionBarDrawerToggle, you must call it during onPostCreate() and onConfigurationChanged().
	 */
	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggles.
		mDrawerToggle.onConfigurationChanged(newConfig);
	}





	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

    @Override
    public void onBackPressed() {
    	// Clicking TWICE the back button to exit activity.
    	// You may also add condition in case of Fragment-based add.
    	// 		if (doubleBackToExitPressedOnce || fragmentManager.getBackStackEntryCount() != 0) 
        if (mRecentlyBackPressed) {
            mExitHandler.removeCallbacks(mExitRunnable);
            mExitHandler = null;
            super.onBackPressed();
        } else {
            mRecentlyBackPressed = true;
            Toast.makeText(this, "Press twice to EXIT.", Toast.LENGTH_SHORT).show();
            mExitHandler.postDelayed(mExitRunnable, delay);
        }
    }

}
